package com.jzsm.common.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@RequiredArgsConstructor
public class RedisUtils {
    private final RedisTemplate<String, String> cmsLicenseRedis;

    public boolean hasKey(String key) {
        return cmsLicenseRedis.hasKey(key);
    }

    public String get(String key) {
        return cmsLicenseRedis.opsForValue().get(generateGroupPrefixKey(key));
    }

    public boolean set(String key, String value) {
        try {
            cmsLicenseRedis.opsForValue().set(generateGroupPrefixKey(key), value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    private String getCuurentGroupId() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        return request.getParameter(ConstantsUtils.GROUP_ID_KEY);
    }

    private String generateGroupPrefixKey(String key) {
        String groupId = getCuurentGroupId();
        return "groupid_" + groupId + "_" + key;
    }


    /**
     * 设置 b2b 用户token
     *
     * @param userId
     * @param token
     * @return
     */
    public boolean setB2bUserToken(String userId, String token) {
        try {
            String key = generateB2bUserTokenKey(userId);
            cmsLicenseRedis.opsForValue().set(key, token);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String getB2bUserToken(String userId) {
        return cmsLicenseRedis.opsForValue().get(generateB2bUserTokenKey(userId));
    }

    private String generateB2bUserTokenKey(String userId) {
        return generateGroupPrefixKey("b2b_user_id_") + userId + "_token";
    }
}
